﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Yoze.Common;
using Yoze.Common.Config;
using Yoze.Common.Messaging;
using Yoze.Common.Querying;

namespace Yoze.Services.Common
{
    /// <summary>
    /// Represents that the implemented classes are Web API controllers
    /// that can provide the access to some basic facilities for microservice
    /// scenarios.
    /// </summary>
    /// <typeparam name="TService">The type of the microservice.</typeparam>
    public abstract class MicroserviceApiController<TService> : ApiController
        where TService : Microservice
    {
        private readonly YozeConfiguration configuration;
        private readonly ICommandPublisher commandPublisher;
        private readonly ITableDataGateway tableDataGateway;

        /// <summary>
        /// Initializes a new instance of <c>MicroserviceApiController{TService}</c> class.
        /// </summary>
        /// <param name="configuration">The configuration instance of Yoze application.</param>
        /// <param name="commandSender">The command sender instance.</param>
        /// <param name="tableGatewayRegistration">The table gateway registration.</param>
        protected MicroserviceApiController(YozeConfiguration configuration,
            ICommandPublisher commandSender,
            IEnumerable<Lazy<ITableDataGateway, NamedMetadata>> tableGatewayRegistration)
        {
            this.configuration = configuration;
            this.commandPublisher = commandSender;
            this.tableDataGateway = tableGatewayRegistration.First(x => x.Metadata.Name == $"{typeof(TService).FullName}.TableDataGateway").Value;
        }

        /// <summary>
        /// Gets the instance of <see cref="YozeConfiguration"/>.
        /// </summary>
        protected YozeConfiguration YozeConfiguration => configuration;

        /// <summary>
        /// 获取消息队列(命令类型)发布者 实例
        /// </summary>
        protected ICommandPublisher CommandPublisher => commandPublisher;

        /// <summary>
        /// 获取数据库 ITableDataGateway 操作实例
        /// </summary>
        protected ITableDataGateway TableDataGateway => tableDataGateway;
    }
}
